package swings.mycomponent.panel;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * @Title: JBackgroundImagePanel.java
 * @Description: TODO(有背景图片的 panel)
 * @author H819
 * @date 2011-3-3
 * @version V1.0
 */

public class JBackgroundImagePanel extends JPanel {

	private static final long serialVersionUID = 6702278957072713279L;
	private Icon backGroundImage;

	public JBackgroundImagePanel() {
	}

	protected void paintComponent(Graphics g) {
		
		if (null != backGroundImage) {
			processBackground(g);
		}
		
		System.out.println("paintComponent(Graphics g)");
	}

	public void setBackground(Icon wallpaper) {
		this.backGroundImage = wallpaper;
		this.repaint();
	}

	private void processBackground(Graphics g) {
		ImageIcon icon = (ImageIcon) backGroundImage;
		Image image = icon.getImage();
		int cw = getWidth();
		int ch = getHeight();
		int iw = image.getWidth(this);
		int ih = image.getHeight(this);
		int x = 0;
		int y = 0;
		while (y <= ch) {
			g.drawImage(image, x, y, this);
			x += iw;
			if (x >= cw) {
				x = 0;
				y += ih;
			}
		}
	}

	// 测试
	public static void main(String[] args) {
		JFrame frame = new JFrame();
		frame.setSize(256, 256);

		Container contentPane = frame.getContentPane();
		contentPane.setLayout(new BorderLayout());

		JBackgroundImagePanel backgroundPanel = new JBackgroundImagePanel();

		backgroundPanel.setBackground(new ImageIcon(JBackgroundImagePanel.class
				.getClass().getResource("/swing/source/image/java-duke-logo.png")));

		contentPane.add(backgroundPanel);

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);

	}
}
